package com.xyz.dao.logic;

import com.xyz.dao.dao.CCustomerDao;
import com.xyz.dao.dao.CCustomeraccntlogDao;
import com.xyz.domain.exception.DbOperateException;
import com.xyz.domain.table.CCustomer;
import com.xyz.domain.table.CCustomeraccntlog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public class CustomerLogic {

    @Autowired
    private CCustomeraccntlogDao accntLogDao;

    @Autowired
    private CCustomerDao customerDao;

    public CCustomer selectByMobile(String mobile){
        return customerDao.selectByMobile(mobile);
    }

    public boolean isUserNameExists(CCustomer customer){
        Integer cnt = customerDao.isUserExists(customer);
        return cnt > 0;
    }

    public CCustomer getByKey(Integer custId){
        return customerDao.select(custId);
    }



    @Transactional
    public CCustomer register(CCustomer customer, CCustomeraccntlog accntLog){
        customer = customerDao.insert(customer);
        if(accntLog == null){
            accntLogDao.insert(accntLog);
        }
        return customer;
    }

    public Integer udpCustomerInfo(CCustomer customer){
        return customerDao.update(customer);
    }

    @Transactional
    public Integer userBindEvent(CCustomer customer,CCustomeraccntlog accntLog){
        int res = customerDao.update(customer);
        if(res == 0){
            return 0;
        }
        if(accntLog.getId() > 0){
            res = accntLogDao.update(accntLog);
        }else{
            accntLog = accntLogDao.insert(accntLog);
            if(accntLog.getId() == null || accntLog.getId() == 0){
                res = 0;
            }
        }
        if(res == 0){
            throw new DbOperateException("更新失败");
        }
        return res;
    }

    public List<CCustomer> list(CCustomer customer, String orderBy){
        return customerDao.selectList(customer, orderBy);
    }

    public CCustomer getByRecommendCode(String recommendCode){
        CCustomer customer = customerDao.selectByRecommendCode(recommendCode);
        if(customer == null){
            return null;
        }else{
            return customer;
        }
    }

    public Integer udpCustmerPassword(CCustomer customer){
        return customerDao.udpCustmerPassword(customer);
    }

    public CCustomer add(CCustomer customer){
        return customerDao.insert(customer);
    }

    public CCustomer insertUserInfo(CCustomer customer){
        return customerDao.insertUserInfo(customer);
    }
}
